<template>
	<xn-form-container
		title="新建分类"
		:width="750"
		:visible="visible"
		:destroy-on-close="true"
		:bodyStyle="{ 'padding-top': '20px' }"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" :label-col="labelCol">
			<a-form-item label="分类编码：" name="code">
				<a-input v-model:value="formData.code" placeholder="请输分类编码" allow-clear />
			</a-form-item>
			<a-form-item label="分类名称：" name="name">
				<a-input v-model:value="formData.name" placeholder="请输入分类名称" allow-clear />
			</a-form-item>
			<a-form-item label="排序：" name="sort">
				<a-input-number style="width: 100%" v-model:value="formData.sort" :max="100" />
			</a-form-item>
			<a-form-item label="备注：" name="remark">
				<a-input v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="trademarkForm">
	import { required } from '@/utils/formRules'
	import TrademarkCatalogApi from '@/api/info/TrademarkCatalogApi'
	// 表单固定label实现
	const labelCol = ref({
		style: {
			width: '100px'
		}
	})

	// 定义emit事件
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const formRef = ref()
	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const submitLoading = ref(false)
	const parentId = ref(0)
	// 默认要校验的
	const formRules = {
		code: [required('请输分类编码')],
		name: [required('请输入分类名称')],
		sort: [required('请选择排序')]
	}

	// 打开抽屉
	const openTrademarkForm = (record) => {
		visible.value = true
		formData.value.flag = 0
		formData.value.status = 0
		formData.value.level = 0
		if(record){
			parentId.value = record.id
			formData.value.level = record.level+1
		}
		formData.value.parentId = parentId.value
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		emit('successful')
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			submitLoading.value = true
			TrademarkCatalogApi.submitForm(formData.value, formData.value.id).then(() => {
				visible.value = false
				submitLoading.value = false
				emit('successful')
			})
		})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		openTrademarkForm
	})
</script>
